<?php

namespace App\HttpController\Applet\Bobo;

use App\Model\WechatsModel;
use App\Utility\Cache;
use App\Utility\CacheDatas;
use Carbon\Carbon;
/**
 * @description 视频控制器
 */
class IndexController extends AuthController {

    public function index(){
        $request= $this->request();
        $chanel = trim($request->getRequestParam('chanel_id')) ?: 0;
        $option = trim($request->getRequestParam('option')) ?: 0;

        $cacheName = 'datas-'.$this->applet.'-'.$chanel;
        $cache = new CacheDatas();
        if(empty($cache->has($cacheName))){
            $appletVideoName = $this->appletVideoModel($this->applet);
            $model = new $appletVideoName;
            $videoTableName = 'videos_'.$this->applet;
            $list = $model->select($videoTableName.'.id,'
                .$videoTableName.'.title,'
                .$videoTableName.'.thumb,'
                .$videoTableName.'.link,'
                .$videoTableName.'.cateid,categorys.name,categorys.thumb as avatar')
                ->where(function($query) use($chanel,$option){
                    if ($chanel){
                        $query->where('chanel_id',$chanel);
                    }
                    if ($option){
                        $query->where('`option`',2);
                    }
                })
                ->where('status',1)
                ->join('categorys',$videoTableName.'.cateid = categorys.id','LEFT')
                ->get();
            $cache->sAddBatch($cacheName,$list,$this->cacheTime);
            unset($model);
        }
        $lists = $cache->sRandBatch($cacheName,40);
        unset($cache);
        return $this->writeJson(0,$lists);
    }

    /**
     * 获取详情
     * @return bool
     * @throws \Exception
     */
    public function info(){
        $request= $this->request();
        $id = $request->getRequestParam('id');
        $share = $request->getRequestParam('share') ?? null;
        $openid = $request->getRequestParam('openid') ?? '';
        $cacheName = 'info-'.$this->applet.'-id-'.$id;
        $cache = new CacheDatas();
        if(empty($cache->has($cacheName))){
            $appletVideoName = $this->appletVideoModel($this->applet);
            $model = new $appletVideoName;
            $info = $model->select('id,title,thumb,link,userid')->find($id);
            if(!$info){
                //数据不存在随机返回一条信息
                $info = $model->select('id,title,thumb,link,userid')->inRandomOrder()->first();
            }
            $cache->set($cacheName,$info,$this->cacheTime);
            unset($model);
        }
        $data = $cache->get($cacheName);
        unset($cache);

        //匹配腾讯视频的vid
        if(strlen($data['link']) !== 11){
            preg_match_all('/\/([0-9a-zA-Z]+).html/', $data['link'], $matchs);
            $vid = $matchs[1][0] ?: '';
            $data['vid'] = $vid;
        }else{
            $data['vid'] = $data['link'];
        }

        //开启任务-创建统计自增推送队列
        $queueData = [
            'id' => $id,
            'admin_id' => $data['userid'],
            'share' => $share,
            'openid' => $openid,
            'applet' => $this->applet,
            'applet_type' => 'video',
        ];
        $queue = new Cache();
        $queue->onQueue('count-inc');
        $queue->push($queueData);
        unset($queue);
        return $this->writeJson(0,$data);
    }

    /**
     * 详情随机列表
     * @return bool
     * @throws \Exception
     */
    public function randList(){
        $cacheName = 'datas-'.$this->applet.'-all';
        $cache = new CacheDatas();
        if(empty($cache->has($cacheName))){
            $appletVideoName = $this->appletVideoModel($this->applet);
            $model = new $appletVideoName;
            $list = $model->select('id,title,thumb,link')
                ->where('status',1)
                ->get();
            $cache->sAddBatch($cacheName,$list,$this->cacheTime);
            unset($model);
        }
        $lists = $cache->sRandBatch($cacheName,20);
        unset($cache);
        return $this->writeJson(0, $lists);
    }

    /**
     * 获取bannner
     * @return bool
     * @throws \Exception
     */
    public function getBanner(){
        $cacheName = 'banners-'.$this->applet;
        $cache = new CacheDatas();
        if(empty($cache->has($cacheName))){
            $appletVideoName = $this->appletVideoModel($this->applet);
            $model = new $appletVideoName;
            $list = $model->select('id,title,thumb,link')
                ->where('banner', 2)
                ->take(5)
                ->get();
            $cache->set($cacheName,$list,$this->cacheTime);
            unset($model);
        }
        $lists = $cache->get($cacheName);
        unset($cache);
        return $this->writeJson(0, $lists);
    }

    /**
     * 收集模板消息的formid
     * @return bool
     * @throws \Exception
     */
    public function formId(){
        $request = $this->request();
        $openid = trim($request->getRequestParam('openid')) ?: '';
        $formid = trim($request->getRequestParam('formid')) ?: '';
        if($formid =='the formId is a mock one'){
            return $this->writeJson(1,null,'测试数据');
        }
        if(!$openid || !$formid){
            return $this->writeJson(1,null,'参数错误');
        }
        $queue = new Cache();
        $queue->onQueue('formid');
        $queue->push([
            'openid' => $openid,
            'expire' => Carbon::now()->addDays(7)->timestamp,
            'formid' => $formid,
            'name'   => $this->applet
        ]);
        unset($queue);
        return $this->writeJson(0);
    }

    /**
     * 获取固定配置
     * @return bool
     * @throws \Exception
     */
    public function config(){
        $request = $this->request();
        $name = trim($request->getRequestParam('name')) ?: '';
        if(!$name){
            return $this->writeJson(1,null,'参数不正确');
        }
        $cacheName = 'links-'.$this->applet.'-configs-'.$name;
        $cache = new CacheDatas();
        $hasCache = $cache->has($cacheName);
        if(!$hasCache){
            $appletVideoName = $this->appletConfigModel($this->applet);
            $model = new $appletVideoName;
            $info = $model->select('value')->where('name',$name)->first();
            $cache->set($cacheName,$info['value'],$this->cacheTime);
            unset($model);
        }
        $link = $cache->get($cacheName);
        unset($cache);
        return $this->writeJson(0,['value' => $link]);
    }

    /**
     * 获取公众号链接文章
     */
    public function wechatLink(){
        $request = $this->request();
        $position = $request->getRequestParam('position') ?? 1;
        $cache = new CacheDatas();
        $cacheName = 'wechat-'.$this->applet.'-position-'.$position;
        if(empty($cache->has($cacheName))){
            $appletModel = new WechatsModel();
            $list = $appletModel->where('position',$position)
                ->where('name',$this->applet)
                ->take(10)
                ->get();
            $cache->set($cacheName,$list,$this->cacheTime);
            unset($model);
        }
        $lists = $cache->get($cacheName);
        unset($cache);
        return $this->writeJson(0,$lists);
    }

    /**
     * 获取预约状态
     */
    public function reserve(){
        $request= $this->request();
        $params = $request->getRequestParam();
        if(!$params['openid']){
            return $this->writeJson(1,null,'参数不正确');
        }
        $userModelName = $this->appletUserModel($this->applet);
        $userModel = new $userModelName;
        $userInfo = $userModel->where('openid',$params['openid'])->first();

        return $this->writeJson(0,['status'=>$userInfo['status']],'ok');
    }

    /**
     * 更新预约状态
     */
    public function reserveUpdate(){
        $request= $this->request();
        $params = $request->getRequestParam();
        if(!$params['status']){
            $params['status'] = 1;
        }
        if(!$params['openid']){
            return $this->writeJson(1,null,'参数不正确');
        }
        $userModelName = $this->appletUserModel($this->applet);
        $userModel = new $userModelName;
        $userInfo = $userModel->where('openid',$params['openid'])->first();
        if($userInfo){
            if($userInfo['status'] == $params['status']){
                return $this->writeJson(0,null,'ok');
            }
            $userInfo['status'] = $params['status'];
            $isUpdate = $userModel->update($userInfo);
            if($isUpdate){
                return $this->writeJson(0,null,'ok');
            }
            return $this->writeJson(1,null,'error');
        }
        return $this->writeJson(1,null,'error:'.$params['openid']);
    }
}
